module HTMr
  class Application
    def method_missing(name, *args, &block)
      if @type == :js
        @cur_elem = name
      else
        if name == :on
          # TODO: do something with javascript
        else
          name = :p if name == :para
          @elem_depth[name] = {:properties => {}}
          unless args[0].class == Hash
            @elem_depth[name][:properties].merge!({ :text => args[0] })
            args.delete_at 0
          end
          @elem_depth[name][:properties].merge!(args[0]) unless args.empty?
          old_elem_depth = @elem_depth
          prev_elem = @cur_elem
          @elem_depth = @elem_depth[name]
          @cur_elem = name
          instance_eval &block if block
          @cur_elem = prev_elem
          @elem_depth = old_elem_depth
        end
      end
    end
    
    def p *args, &block
      para *args, &block
    end
    
    def initialize(title, &block)
      puts "Creating new app called '#{title}'"
      @elements = {
        :html => {
          :head => {
            :title => {
              :properties => {
                :text => title
              }
            }
          },
          :body => {}
        }
      }
      @elem_depth = @elements[:html][:body]
      @cur_elem = :body
      @type = :html
      @indent = 0
      instance_eval &block if block
    end
    
    def render
      render_each @elements
    end
    
    private
    def generate_js_from_block &block
      @type = :js
      instance_eval &block
      @type = :html
    end
    
    def render_each elements
      render = ""
      elements.each do |element, hash|
        if element == :properties
          render = element
          break
        else  
          @indent += 1
          props = ""
          text = ""
          content = render_each(hash)
          if content == :properties
            properties = hash[:properties]
            properties.each do |property, value|
              if property == :text
                text << value
              else
                props << " #{property.to_s}=\"#{value}\""
              end
            end
            
            hash.delete(:properties)
            content = render_each(hash)
          end
          text = "#{"  " * @indent}#{text}\n" unless text == ""
          render << "#{"  " * (@indent - 1)}<#{element.to_s}#{props}>\n#{text}#{content}#{"  " * (@indent -1 )}</#{element.to_s}>\n"
          @indent -= 1
        end
      end
      render
    end
  end
end